package com.vehiclemanagement.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vehiclemanagement.common.ResponseResult;
import com.vehiclemanagement.entity.VehicleInspection;
import com.vehiclemanagement.service.VehicleInspectionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 车辆年检记录管理控制器
 */
@RestController
@RequestMapping("/vehicleInspection")
@Api(tags = "车辆年检记录管理")
@Slf4j
public class VehicleInspectionController {

    @Autowired
    private VehicleInspectionService vehicleInspectionService;

    /**
     * 分页查询年检记录
     */
    @GetMapping("/page")
    @ApiOperation(value = "分页查询年检记录", notes = "根据条件分页查询年检记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页码", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "size", value = "每页数量", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "searchTerm", value = "搜索关键词（车牌号/年检地点/年检公司/负责人/证书编号）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "vehicleId", value = "车辆ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "inspectionType", value = "年检类型(1:定期检查,2:年检,3:环保检测,4:综合检测)", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "inspectionResult", value = "年检结果(1:通过,2:不通过)", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态(0:未开始,1:进行中,2:已完成,3:已取消)", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "String", paramType = "query")
    })
    public ResponseResult<IPage<VehicleInspection>> page(
            @RequestParam Integer current,
            @RequestParam Integer size,
            @RequestParam(required = false) String searchTerm,
            @RequestParam(required = false) Long vehicleId,
            @RequestParam(required = false) Integer inspectionType,
            @RequestParam(required = false) Integer inspectionResult,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        
        log.info("分页查询年检记录: current={}, size={}, searchTerm={}, vehicleId={}, inspectionType={}, inspectionResult={}, status={}, startTime={}, endTime={}",
                current, size, searchTerm, vehicleId, inspectionType, inspectionResult, status, startTime, endTime);
        
        IPage<VehicleInspection> page = vehicleInspectionService.pageInspections(
                current, size, searchTerm, vehicleId, inspectionType, inspectionResult, status, startTime, endTime);
        
        return ResponseResult.success(page);
    }

    /**
     * 获取年检记录详情
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "获取年检记录详情", notes = "根据ID获取年检记录详细信息")
    @ApiImplicitParam(name = "id", value = "年检记录ID", required = true, paramType = "path", dataType = "Long")
    public ResponseResult<VehicleInspection> getById(@PathVariable Long id) {
        log.info("获取年检记录详情: id={}", id);
        
        VehicleInspection inspection = vehicleInspectionService.getInspectionById(id);
        if (inspection == null) {
            return ResponseResult.fail("未找到该年检记录");
        }
        
        return ResponseResult.success(inspection);
    }

    /**
     * 添加年检记录
     */
    @PostMapping
    public ResponseResult<Boolean> add(@RequestBody VehicleInspection inspection) {
        log.info("添加年检记录: {}", inspection);
        
        if (inspection.getVehicleId() == null) {
            return ResponseResult.fail("车辆ID不能为空");
        }
        
        boolean result = vehicleInspectionService.addInspection(inspection);
        if (result) {
            return ResponseResult.success(true, "添加成功");
        } else {
            return ResponseResult.fail("添加失败");
        }
    }

    /**
     * 更新年检记录
     */
    @PutMapping
    public ResponseResult<Boolean> update(@RequestBody VehicleInspection inspection) {
        log.info("更新年检记录: {}", inspection);
        
        if (inspection.getId() == null) {
            return ResponseResult.fail("年检记录ID不能为空");
        }
        
        boolean result = vehicleInspectionService.updateInspection(inspection);
        if (result) {
            return ResponseResult.success(true, "更新成功");
        } else {
            return ResponseResult.fail("更新失败");
        }
    }

    /**
     * 删除年检记录
     */
    @DeleteMapping("/{id}")
    public ResponseResult<Boolean> delete(@PathVariable Long id) {
        log.info("删除年检记录: id={}", id);
        
        boolean result = vehicleInspectionService.deleteInspection(id);
        if (result) {
            return ResponseResult.success(true, "删除成功");
        } else {
            return ResponseResult.fail("删除失败");
        }
    }

    /**
     * 开始年检
     */
    @PostMapping("/start/{id}")
    public ResponseResult<Boolean> startInspection(@PathVariable Long id) {
        log.info("开始年检: id={}", id);
        
        boolean result = vehicleInspectionService.startInspection(id);
        if (result) {
            return ResponseResult.success(true, "操作成功");
        } else {
            return ResponseResult.fail("操作失败");
        }
    }

    /**
     * 完成年检
     */
    @PostMapping("/complete/{id}")
    public ResponseResult<Boolean> completeInspection(
            @PathVariable Long id,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime inspectionDate,
            @RequestParam(required = false) BigDecimal inspectionCost,
            @RequestParam Integer inspectionResult,
            @RequestParam(required = false) String failReason,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime validStartDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime validEndDate,
            @RequestParam(required = false) String certificateNumber,
            @RequestParam(required = false) String remark) {
        
        log.info("完成年检: id={}, inspectionDate={}, inspectionCost={}, inspectionResult={}, failReason={}, validStartDate={}, validEndDate={}, certificateNumber={}, remark={}",
                id, inspectionDate, inspectionCost, inspectionResult, failReason, validStartDate, validEndDate, certificateNumber, remark);
        
        boolean result = vehicleInspectionService.completeInspection(
                id, inspectionDate, inspectionCost, inspectionResult, failReason, 
                validStartDate, validEndDate, certificateNumber, remark);
        
        if (result) {
            return ResponseResult.success(true, "操作成功");
        } else {
            return ResponseResult.fail("操作失败");
        }
    }

    /**
     * 取消年检
     */
    @PostMapping("/cancel/{id}")
    public ResponseResult<Boolean> cancelInspection(
            @PathVariable Long id,
            @RequestParam(required = false) String remark) {
        
        log.info("取消年检: id={}, remark={}", id, remark);
        
        boolean result = vehicleInspectionService.cancelInspection(id, remark);
        if (result) {
            return ResponseResult.success(true, "操作成功");
        } else {
            return ResponseResult.fail("操作失败");
        }
    }

    /**
     * 获取车辆年检总费用
     */
    @GetMapping("/cost/total/{vehicleId}")
    public ResponseResult<BigDecimal> getTotalCost(@PathVariable Long vehicleId) {
        log.info("获取车辆年检总费用: vehicleId={}", vehicleId);
        
        BigDecimal totalCost = vehicleInspectionService.sumInspectionCostByVehicleId(vehicleId);
        return ResponseResult.success(totalCost);
    }

    /**
     * 获取车辆年检次数
     */
    @GetMapping("/count/{vehicleId}")
    public ResponseResult<Integer> getInspectionCount(@PathVariable Long vehicleId) {
        log.info("获取车辆年检次数: vehicleId={}", vehicleId);
        
        Integer count = vehicleInspectionService.countInspectionByVehicleId(vehicleId);
        return ResponseResult.success(count);
    }

    /**
     * 按年检类型统计
     */
    @GetMapping("/statistics/type")
    public ResponseResult<List<Map<String, Object>>> statisticsByType(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        
        log.info("按年检类型统计: startTime={}, endTime={}", startTime, endTime);
        
        List<Map<String, Object>> statistics = vehicleInspectionService.statisticsByType(startTime, endTime);
        return ResponseResult.success(statistics);
    }

    /**
     * 按月份统计年检费用
     */
    @GetMapping("/statistics/month")
    public ResponseResult<List<Map<String, Object>>> statisticsByMonth(
            @RequestParam(required = false) Integer year) {
        
        log.info("按月份统计年检费用: year={}", year);
        
        List<Map<String, Object>> statistics = vehicleInspectionService.statisticsByMonth(year);
        return ResponseResult.success(statistics);
    }

    /**
     * 查询需要年检的车辆
     */
    @GetMapping("/vehicle/reminder")
    public ResponseResult<List<Map<String, Object>>> getVehiclesNeedingInspection(
            @RequestParam(required = false) Integer daysThreshold) {
        
        log.info("查询需要年检的车辆: daysThreshold={}", daysThreshold);
        
        List<Map<String, Object>> vehicles = vehicleInspectionService.findVehiclesNeedingInspection(daysThreshold);
        return ResponseResult.success(vehicles);
    }
} 